<template>
  <div id="aduit">
    <div class="container">
      <div class="common-detail">
        <div class="info-title">基本信息</div>
        <div class="info-box">
          <info-table :data="infoTable" />
        </div>
        <div class="info-title">任务反馈</div>
        <DataTable
          rowKey="goodsCode"
          :showConfig="false"
          :btns="(alias === 'edit' && btns) || []"
          :tableData="Data"
          :expand="true"
          :tableColumn="tableColumn"
          :rowSelection="{ selectedRowKeys: deleteList, onChange: chooseBack }"
          :pageConfig="pageConfig"
        >
          <template slot="expand" slot-scope="{ index, data }">
            <div class="expand-box">
              <Upload :defaultList="data.countingTaskGoodsFiles" :disabled="alias === 'detail'" @change="handleUpload" @click="clickUpload(index)" :limit="6" />
            </div>
          </template>
        </DataTable>
        <!-- 已完成、已驳回状态显示 -->
        <template v-if="checkData.length!==0">
          <div style="margin-top: 24px"  v-for="(item,index) in checkData" :key="index">
            <div class="info-title">审核信息</div>
            <div class="info-body">
              <a-row class="body-row">
                <a-col :span="3" class="row-left">审核人</a-col>
                <a-col :span="6" class="row-right">{{item.adminUser}}</a-col>
                <a-col :span="3" class="row-left">审核时间</a-col>
                <a-col :span="6" class="row-right">{{item.createTime}}</a-col>
              </a-row>
              <a-row class="body-row">
                <a-col :span="3" class="row-left">审核意见</a-col>
                <a-col :span="6" class="row-right">{{item.auditResult==='Y'?'通过':'不通过'}}</a-col>
                <a-col :span="3" class="row-left">审核说明</a-col>
                <a-col :span="6" class="row-right">{{item.remark}}</a-col>
              </a-row>
            </div>
          </div>
        </template>
        <!-- 待审核状态 -->
        <div style="margin-top: 24px" v-if="['DSH','DZH'].includes(detailData.detailState) && viewType === 'check'">
           <div class="info-title">审核处理</div>
          <Audit :form="checkForm" @confirm="handleConfirm" />
        </div>
        <div class="footer-btns" v-if="['DWC', 'DTJ', 'BH'].includes(detailData.detailState) && alias === 'edit'">
          <a-button type="primary" @click="handleSave" style="margin-right: 12px">保存</a-button>
          <a-button type="primary" @click="handleSubmit" v-if="isSubmit">提交</a-button>
        </div>
      </div>
    </div>
    <!-- 选择物资弹窗 -->
    <a-modal
      title="选择物资"
      width="800px"
      :visible="formVisible"
      @ok="handleChoose"
      @cancel="handleCancel"
    >
      <a-row>
        <a-col :span="4">
          <!-- <a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
          <a-tree
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="treeData"
            @expand="onExpand"
          >
          </a-tree> -->
          <a-cascader
            v-model="ncMaterielId"
            :options="materialList"
            :fieldNames="{ label: 'name', value: 'id', children: 'children' }"
            placeholder="请选择物资编号"
            style="width:400px"
            change-on-select
            @change="getNcMaterialList"
          />
        </a-col>
        <a-col :span="24">
          <DataTable
            rowKey="goodsCode"
            :tableData="materialData"
            :tableColumn="materialTableColumn"
            :pageConfig="materialPageConfig"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            @refresh="getNcMaterialList"
          />
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>
<script lang='ts'>
import { Validate, Confirm } from '@/decorator';
import { Component, Watch, Vue } from 'vue-property-decorator';

const getParentKey = (key: any, tree: any): any => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item: any) => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const dataList: any[] = []
const generateList = (data: any) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.key;
    dataList.push({ key, title: key });
    if (node.children) {
      generateList(node.children);
    }
  }
};

@Component
export default class aduit extends Vue {
  checkForm: any = {}
  infoTable: any[] = [];

  id: string = '';
  Data: any[] = [];
  tableColumn: any = {
    goodsCode: {
      label: '材料编码'
    },
    ncMaterielName: {
      label: '材料名称'
    },
    goodsUnit: {
      label: '单位'
    },
    // before_num: {
    //   label: '规格',
    //   width: 120
    // },
    // later_num: {
    //   label: '单位',
    //   width: 120
    // },
    stockNum: {
      label: '库存量',
      type: 'inputNumber',
      disabled: this.alias !== 'edit',
      cat: 'price',
      pre: ''
    },
    goodsSum: {
      label: '闲置可周转数量',
      type: 'inputNumber',
      disabled: this.alias !== 'edit',
      cat: 'price',
      pre: ''
    },
    action: {
      label: '操作',
      width: 230,
      template: [
        {
          tag: 'a',
          text: '删除',
          callback: this.delHandle,
          show: this.alias !== 'detail'
        }
      ]
    }
  };
  pageConfig: any = {
    current: 1,
    total: 0,
    pageSize: 10,
    onChange: this.changePage
  };
  get btns () {
    return [
    {
      label: '选择物资',
      callback: this.chooseMaterial
    },
    {
      label: '删除',
      callback: () => this.delHandle(null, this.deleteList)
    }
    // {
    //   label: '表格导入',
    //   callback: () => this.delHandle(null, this.deleteList)
    // }
  ];
  }
  selectedRowKeys: any[] = [];
  options: any[] = [];
  formVisible: boolean = false; // 选择物资
  skuOptions: any[] = []; // 规格
  checkData: any = [] // 审核信息
  expandedKeys: any[] = []
  searchValue: string = ''
  autoExpandParent: boolean = true
  treeData: any[] = [
    {
      title: '1',
      key: '1',
      children: [
        {
          title: '1-1',
          key: '1-1'
        }
      ]
    },
    {
      title: '2',
      key: '2',
      children: [
        {
          title: '2-1',
          key: '2-1'
        }
      ]
    }
  ]
  materialData: any = [] // 物资列表
  materialTableColumn: any = {
    ncMaterielId: {
      label: '物资编码',
      width: 120
    },
    ncMaterielName: {
      label: '物资名称',
      width: 200
    }
    // before_num: {
    //   label: '规格',
    //   width: 120
    // },
    // later_num: {
    //   label: '型号',
    //   width: 120
    // },
    // later_num1: {
    //   label: '单位',
    //   width: 120
    // },
    // change_price: {
    //   label: '采购价',
    //   width: 120
    // }
  };
  materialPageConfig: any = {
    current: 1,
    total: 0,
    pageSize: 10,
    onChange: this.changeMaterialPage
  };
  selectData: any = [] // 选择的物资
  detailData: any = {} // 详情数据
  uploadIndex: number = 0
  isSubmit: boolean = false // 是否保存完
  stateMap: any = {
    'BH': '驳回',
    'YWC': '同意'
  }
  deleteList: any = [] // 删除数组
  ncMaterielId: string[] = []
  materialList: any[] = []
  treeId: string = ''
  get alias () {
    return this.$route.query._alias;
  }
  get taskDetailId () {
    return this.$route.query.taskDetailId
  }
  get viewType () {
    return this.$route.query.type
  }
  onExpand (expandedKeys: any[]) {
    this.expandedKeys = expandedKeys;
    this.autoExpandParent = false;
  }
  onChange (e: any) {
    const value = e.target.value;
    const expandedKeys = dataList
      .map((item: any) => {
        if (item.title.indexOf(value) > -1) {
          return getParentKey(item.key, this.treeData);
        }
        return null;
      })
      // .filter((item: any, i: any, self: any) => item && self.indexOf(item) === i);

    Object.assign(this, {
      expandedKeys,
      searchValue: value,
      autoExpandParent: true
    });
  }
  // 树的选择
  handleSelectTree () {}

  init () {
    this.id = this.$route.query.id as string;
    generateList(JSON.parse(JSON.stringify(this.treeData)))
    this.getDetail()
    this.getTaskAudit()
    // this.getList()
    // this.getMaterialList()
  }
  // 获取审核信息
  getTaskAudit () {
    this.$api.countingTaskAuditFetch({taskDetailId: this.taskDetailId}).then((res:any) => {
      this.checkData = res.data
    })
  }
  getDetail () {
    let data = { taskDetailId: this.taskDetailId }
    this.$api.countingTaskMonitorDetailFetch(data).then((res: any) => {
      const that = res.data
      let { detailState } = res.data
      that.sh_yj = this.stateMap[detailState] || ''
      let { taskInfo, checkInfo } = this.$enums.allot
      this.infoTable = Object.keys(taskInfo).map((key: any) => ({label: taskInfo[key], value: (this.$enums.allot[key] || {})[res.data[key]] || res.data[key]}))
      // this.checkData = Object.keys(checkInfo).map((key: any) => ({label: checkInfo[key], value: (this.$enums.allot[key] || {})[res.data[key]] || res.data[key]}))
      let goodsList = res.data.countingTaskGoodsBeans.map((item: any) => ({
        ...item,
        countingTaskGoodsFiles: item.countingTaskGoodsFiles.map((ele: any, index: number) => ({
          uid: -index - 1,
          url: ele.url,
          name: ele.url
        }))
      }))
      this.Data = goodsList
      this.detailData = res.data
    })
  }
  getList () {
    const { current: page, pageSize: size } = this.pageConfig;
    const data = {
      page,
      size,
      id: this.id
    };
    this.$api.resourceManagementPurchaseChangeListFetch(data).then((res: any) => {
      this.Data = res.data.records;
      this.pageConfig.total = res.data.total;
      if (!this.Data.length && this.pageConfig.current > 1) {
        --this.pageConfig.current;
        this.getList();
      }
    });
  }
  changePage (val: number) {
    this.pageConfig.current = val;
    this.getList();
  }
  changeMaterialPage (val: number) {
    this.materialPageConfig.current = val;
    this.getNcMaterialList();
  }
  // 点击上传照片
  clickUpload (index: number) {
    this.uploadIndex = index
  }
  // 上传图片
  handleUpload (fileList: any) {
    this.$set(this.Data[this.uploadIndex], 'countingTaskGoodsFiles', fileList)
  }
  // 点击选择物资
  chooseMaterial () {
    this.formVisible = true;
    this.materialData = []
    this.ncMaterielId = []
    this.materialPageConfig.current = 1
    this.materialPageConfig.total = 0
    this.getMaterialCategoryList()
  }
  // 确认审核
  handleConfirm () {
    let { auditStatus, remark } = this.checkForm
    let data = {
      taskDetailId: this.taskDetailId,
      sh_explain: remark,
      result: auditStatus === 1 ? 'Y' : auditStatus === 2 ? 'N' : ''
    }
    this.$api.countingDownFetch(data).then(() => {
      this.$message.success('审核成功')
      this.$router.back()
    })
  }
  // 任务反馈复选
  chooseBack (selectedRowKeys: string[], row: any) {
    this.deleteList = selectedRowKeys
  }
  // 复选物资
  onSelectChange (selectedRowKeys: string[], row: any) {
    this.selectedRowKeys = selectedRowKeys
    this.selectData = row
  }
  // 选择物资确定
  handleChoose () {
    // this.selectData.forEach((ele: any, index: number) => {
    //   this.$set(this.selectData[index], 'countingTaskGoodsFiles', [])
    //   this.$set(this.selectData[index], 'goodsSum', 0)
    // })
    this.Data = this.Data.concat(this.selectData)
    // let setMap = new Map()
    // this.Data.map((item: any) => setMap.set(item.goodsCode, item))
    // this.Data = [...setMap.values()]
    this.handleCancel()
  }
  handleCancel () {
    this.formVisible = false
    this.selectData = []
    this.selectedRowKeys = []
  }
  // 删除
  @Confirm('', (row?: any, deleteList?: string[]) => {
    return new Promise((resolve, reject) => {
      if (row) {
        // eslint-disable-next-line prefer-promise-reject-errors
        reject({message: 'noConfirm'})
      } else {
        console.log(deleteList!.length);
        // eslint-disable-next-line prefer-promise-reject-errors
        deleteList!.length ? resolve({content: '你确定要删除所选的材料吗？'}) : reject({message: '请勾选要删除的材料'})
      }
    })
  })
  delHandle (row?: any, deleteList?: string[]) {
    const key = 'goodsCode'
    console.log('删除', row)
    console.log('删除', this.Data)
    if (row) {
      this.Data.splice(this.Data.findIndex(item => item[key] === row[key]), 1)
    } else {
      // 删除多个
      this.deleteList.map((key: any) => this.Data.splice(this.Data.findIndex(item => item[key] === key), 1))
      this.deleteList = []
    }
  }

  // 保存
  handleSave () {
    let submitData = JSON.parse(JSON.stringify(this.Data))
    submitData.forEach((ele: any) => {
      ele.countingTaskGoodsFiles = ele.countingTaskGoodsFiles.map((item: any) => ({
        url: this.$util.getPicUrl(item)
      }))
    })
    submitData = submitData.map((item:any) => ({
      goodsCode: item.ncMaterielId,
      ncMaterielId: item.ncMaterielId,
      ncMaterielName: item.ncMaterielName,
      stockNum: item.stockNum,
      goodsSum: item.goodsSum
    }))
    let data = {
      countingTaskGoodsBeans: submitData,
      taskDetailId: this.taskDetailId
    }
    this.$api.countingSaveTaskGoodsFetch(data).then(() => {
      this.$message.success('保存成功')
      this.isSubmit = true
    })
  }
  // 提交
  handleSubmit () {
    let data = {
      taskDetailId: this.taskDetailId
    }
    this.$api.countingTaskMonitorDetailDowFetch(data).then(() => {
      this.$message.success('提交成功')
      this.$router.go(-1)
    })
  }
  // 获取物料数据
  getMaterialCategoryList () {
    this.$api.wuLiaoTierListFetch().then((res: any) => {
      this.materialList = res.data
    })
  }
  getNcMaterialList () {
    if (this.ncMaterielId.length === 0) {
      this.treeId = this.ncMaterielId[0]
    } else {
      this.treeId = this.ncMaterielId[this.ncMaterielId.length - 1]
    }
    let { current, pageSize } = this.materialPageConfig
    let data = {
      page: current,
      size: pageSize,
      id: this.treeId
    }
    this.$api.wuLiaoWuLiaoListFetch(data).then((res: any) => {
      this.materialData = res.data.records.map((item:any) => ({ncMaterielId: item.wuliaoCode, ncMaterielName: item.wuliaoName}))
      this.materialPageConfig.total = res.data.total
      if (!this.materialData.length && this.materialPageConfig.current > 1) {
        --this.materialPageConfig.current
        this.getNcMaterialList()
      }
    })
    // if (this.ncMaterielId.length < 3) return;
    // this.$api.goodsNcMaterielListPageFetch({
    //   id: this.ncMaterielId[this.ncMaterielId.length - 1],
    //   page: this.materialPageConfig.current,
    //   size: this.materialPageConfig.pageSize
    // }).then((res: any) => {
    //   this.materialData = res.data.records.map((item: any) => ({ ncMaterielName: item.wuliaoName, goodsCode: item.wuliaoCode }))
    //   this.materialPageConfig.total = res.data.total;
    // })
  }
}
</script>
<style lang='scss' scoped>
#aduit {
  .financing {
    width: 33%;
    border-right: 1px solid #c9c9c9;
  }
  .loan {
    width: 35%;
    padding-left: 2%;
  }
  .common-detail {
    /deep/.ant-input-number {
      width: 100%;
    }
    .info-box {
      margin-bottom: 24px;
    }
    .time-line {
      margin-top: 20px;
    }
    .form-model {
      margin-top: 20px;
    }
    .audit {
      .input-box {
        width: 300px;
        margin-right: 20px;
      }
      .flex {
        margin-top: 10px;
      }
    }
    .expand-box {
      .expand-title {
        font-weight: 600;
        padding: 10px;
        background-color: #e9e9e9;
      }
      /deep/.table-header {
        margin-bottom: 0;
      }
    }
  }
  .footer-btns{
    display: flex;
    align-items: center;
    margin-top: 24px;
    justify-content: center;
  }
}
// 弹窗
.transfer-box {
  width: 100%;
  border: 1px solid red;
  .box-title {
    color: #000;
    font-weight: 800;
    // margin-bottom: 12px;
  }
  .info-box {
    display: flex;
    flex-direction: column;
    .info-item {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
.info-body{
  .body-row{
    .row-left{
      border: 1px solid #eeeeee;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: #f9fafc;
    }
    .row-right{
      border: 1px solid #eeeeee;
      height: 50px;
      line-height: 50px;
      text-align: center;
    }
  }
}
</style>
